// const baseURL = 'http://1.13.187.226:12269/gfs/var'; // 生产
const baseURL = '/api'; // 测试

// 将对象转换为查询参数字符串
function toQueryString(params = {}) {
	return Object.entries(params)
		.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
		.join('&');
}

// 封装请求函数
function request(method, url, data = {}, customHeaders = {}) {
	const headers = {
		'Content-Type': 'application/json',
		...customHeaders,
	};

	let fullUrl = baseURL + url;
	console.log(fullUrl)
	if (method.toUpperCase() === 'GET' && data && Object.keys(data).length) {
		const queryString = toQueryString(data);
		fullUrl += (fullUrl.includes('?') ? '&' : '?') + queryString;
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: fullUrl,
			method,
			data: method.toUpperCase() === 'GET' ? undefined : data,
			header: headers,
			success: res => {
				if (res.statusCode >= 200 && res.statusCode < 300) {
					resolve(res.data);
				} else {
					reject(res);
				}
			},
			fail: err => {
				reject(err);
			}
		});
	});
}

export const GET = (url, params = {}, headers = {}) => {
	return request('GET', url, params, headers);
}

export const POST = (url, data = {}, headers = {}) => {
	return request('POST', url, data, headers);
}
